package com.sbc.sync;

import org.apache.rocketmq.client.apis.ClientConfiguration;
import org.apache.rocketmq.client.apis.ClientConfigurationBuilder;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.apache.rocketmq.client.apis.producer.SendReceipt;

import java.io.IOException;


/**
 * @description: 同步生产者
 * @author: songbaicheng
 * @create: 2024/9/3 16:50
 **/
public class SyncProducer {
    public static void main(String[] args) throws ClientException, IOException {
        String endpoint = "localhost:8091";
        String topic = "SyncTopic";
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        ClientConfigurationBuilder builder = ClientConfiguration.newBuilder().setEndpoints(endpoint);
        ClientConfiguration configuration = builder.build();

        try (Producer producer = provider.newProducerBuilder()
                .setTopics(topic)
                .setClientConfiguration(configuration)
                .build()) {
            Message message = provider.newMessageBuilder()
                    .setTopic(topic)
                    // 设置消息索引键，可根据关键字精确查找某条消息。
                    .setKeys("SyncMessageKey")
                    // 设置消息Tag，用于消费端根据指定Tag过滤消息。
                    .setTag("SyncMessageTag")
                    // 消息体。
                    .setBody("SyncMessage".getBytes())
                    .build();
            // 发送消息，需要关注发送结果，并捕获失败等异常。
            SendReceipt sendReceipt = producer.send(message);
            System.out.println("Send message successfully, messageId={}" + sendReceipt.getMessageId());
        } catch (ClientException e) {
            System.out.println("Failed to send message" + e);
        }
    }
}
